package org.easy.excel.support.config.entity;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.OutputStream;
import java.io.Serializable;
import java.util.List;

/**
 * 数据流到处支持类
 *
 * @author 李坤
 * @date 2022/11/15 10:58
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExportStreamSupport implements Serializable {

    /**
     * Sheet配置类
     */
    private WriteSheet writeSheet;

    /**
     * 数据流写出类
     */
    private ExcelWriter excelWriter;

    /**
     * 根据给定的数据生成{@link ExportStreamSupport}对象实例
     *
     * @param outputStream 输出流
     * @param writerSheetBuilder {@link WriteSheet}构建器
     * @return {@link ExportStreamSupport}对象实例
     */
    public static ExportStreamSupport getInstance(OutputStream outputStream, ExcelWriterSheetBuilder writerSheetBuilder) {
        final WriteSheet writeSheet = writerSheetBuilder.build();
        return new ExportStreamSupport(writeSheet, EasyExcel.write(outputStream).build());
    }

    /**
     * 将给定的数据写出到Excel流中
     *
     * @param exportData 导出的数据
     *
     * @return {@link ExcelWriter}
     */
    public ExcelWriter writer(List<?> exportData) {
        return excelWriter.write(exportData, writeSheet);
    }

    /**
     * 完成数据写入，关闭IO流
     */
    public void finish() {
        excelWriter.finish();
    }

}
